<?php


namespace app\applet\controller;


use app\utils\JwtUtils;
use think\Controller;
use think\Db;

class Wechat extends Controller
{

    public function getUserInfo(){
        $appid = "wx6e64e3c7372be385";//小程序的唯一标识
        $appsecret = "8c42548e71381ce7668a3cbb7123a162";//小程序的AppSecret
        $openid = 'ol5hW48KjTIJ4ALeXwOfZ_wV-bjw';

        // 获取access_token
        $token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
        $token_json = file_get_contents($token_url);
        $token_arr = json_decode($token_json, true);

        $access_token = $token_arr['access_token'];

        // 获取用户信息
        $user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
        $user_info_json = file_get_contents($user_info_url);
        $user_info_arr = json_decode($user_info_json, true);

        // 打印用户信息
        print_r($user_info_arr);
    }
    public function getUserId(){
        $code = request()->get('auth_code');
        $appid = "wx6e64e3c7372be385";//小程序的唯一标识
        $secret = "8c42548e71381ce7668a3cbb7123a162";//小程序的AppSecret
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';

        $tmpInfo = file_get_contents( $url);//执行操作

        // $tmpInfo = json_decode(json_encode(simplexml_load_string($tmpInfo, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        $tmpInfo = $this->object_to_array(json_decode($tmpInfo));

        if (!empty($tmpInfo['errmsg'])) {
            return json(['code' => '500',"msg"=>$tmpInfo['errmsg']]);
            return $tmpInfo['errmsg'];
        } else {
            $userInfo=Db::table("userinfo")->where("openid",$tmpInfo["openid"])->find();
            if(empty($userInfo)){
                $arr["bindRoomStatus"]=false;
                $arr["openid"]=$tmpInfo["openid"];
                $token=JwtUtils::getToken($arr);
                return json(["code"=>0,'accessToken' => $token,"bindRoomStatus"=>false]);
            }else{
                $arr["uid"]=$userInfo["id"];
                $arr["openid"]=$tmpInfo["openid"];
                $arr["bindRoomStatus"]=false;
                if(!empty($userInfo["room_id"])){
                    $arr["bindRoomStatus"]=true;
                }

                $arr=array_merge($arr,$userInfo);
                $token=JwtUtils::getToken($arr);
                return json(["code"=>0,'accessToken' => $token,"bindRoomStatus"=>$arr["bindRoomStatus"]]);
            }
        }
    }
    public function object_to_array($obj){
        $_arr = is_object($obj) ? get_object_vars($obj) :$obj;
        foreach($_arr as $key=>$val){
            if($key !== 'gioouts'){
                $val = (is_array($val) || is_object($val)) ? $this->object_to_array($val):$val;
                $arr[$key] = $val;
            }
        }
        return $arr;
    }

}